import frappe
import json
import os
from datetime import datetime

def backup_navbar_help_dropdown():
    """
    备份当前的帮助下拉菜单配置
    返回备份文件路径
    """
    try:
        # 获取当前的Navbar Settings
        navbar_settings = frappe.get_single("Navbar Settings")
        
        # 提取help_dropdown数据
        help_dropdown_data = []
        for item in navbar_settings.help_dropdown:
            help_dropdown_data.append({
                "item_label": item.item_label,
                "item_type": item.item_type,
                "route": item.route,
                "action": item.action,
                "is_standard": item.is_standard,
                "hidden": item.hidden,
            })
        
        # 创建备份数据
        backup_data = {
            "timestamp": datetime.now().isoformat(),
            "help_dropdown": help_dropdown_data
        }
        
        # 确保备份目录存在
        backup_dir = os.path.join(frappe.get_app_path("theme"), "backups")
        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)
        
        # 生成备份文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_filename = f"navbar_help_dropdown_backup_{timestamp}.json"
        backup_path = os.path.join(backup_dir, backup_filename)
        
        # 写入备份文件
        with open(backup_path, 'w', encoding='utf-8') as f:
            json.dump(backup_data, f, indent=2, ensure_ascii=False)
        
        print(f"✅ 成功备份帮助下拉菜单配置到: {backup_path}")
        return backup_path
        
    except Exception as e:
        frappe.log_error(f"备份帮助下拉菜单配置时出错: {str(e)}")
        print(f"❌ 备份帮助下拉菜单配置失败: {str(e)}")
        return None


def remove_help_dropdown_items(items_to_remove):
    """
    删除指定的帮助下拉菜单项
    
    Args:
        items_to_remove (list): 要删除的菜单项标签列表
    
    Returns:
        bool: 操作是否成功
    """
    try:
        # 获取Navbar Settings文档
        navbar_settings = frappe.get_single("Navbar Settings")
        
        # 获取当前的help_dropdown项目
        current_items = navbar_settings.help_dropdown
        
        # 过滤掉要删除的项目
        filtered_items = []
        removed_count = 0
        
        for item in current_items:
            if item.item_label not in items_to_remove:
                filtered_items.append(item)
            else:
                removed_count += 1
                print(f"🗑️ 删除帮助菜单项: {item.item_label}")
        
        # 清空原有项目并添加过滤后的项目
        navbar_settings.set("help_dropdown", [])
        
        for item in filtered_items:
            navbar_settings.append("help_dropdown", {
                "item_label": item.item_label,
                "item_type": item.item_type,
                "route": item.route,
                "action": item.action,
                "is_standard": item.is_standard,
                "hidden": item.hidden,
            })
        
        # 保存修改
        navbar_settings.save()
        
        print(f"✅ 成功删除 {removed_count} 个帮助菜单项")
        return True
        
    except Exception as e:
        frappe.log_error(f"删除帮助下拉菜单项时出错: {str(e)}")
        print(f"❌ 删除帮助下拉菜单项失败: {str(e)}")
        return False


def restore_navbar_help_dropdown_from_backup():
    """
    从最新的备份文件恢复帮助下拉菜单配置
    
    Returns:
        bool: 恢复是否成功
    """
    try:
        # 查找最新的备份文件
        backup_dir = os.path.join(frappe.get_app_path("theme"), "backups")
        
        if not os.path.exists(backup_dir):
            print("⚠️ 备份目录不存在，无法恢复")
            return False
        
        # 获取所有备份文件
        backup_files = [f for f in os.listdir(backup_dir) if f.startswith("navbar_help_dropdown_backup_") and f.endswith(".json")]
        
        if not backup_files:
            print("⚠️ 未找到帮助下拉菜单备份文件")
            return False
        
        # 选择最新的备份文件
        backup_files.sort(reverse=True)
        latest_backup = backup_files[0]
        backup_path = os.path.join(backup_dir, latest_backup)
        
        # 读取备份数据
        with open(backup_path, 'r', encoding='utf-8') as f:
            backup_data = json.load(f)
        
        # 获取Navbar Settings文档
        navbar_settings = frappe.get_single("Navbar Settings")
        
        # 清空当前的help_dropdown
        navbar_settings.set("help_dropdown", [])
        
        # 恢复备份的项目
        restored_count = 0
        for item_data in backup_data.get("help_dropdown", []):
            navbar_settings.append("help_dropdown", item_data)
            restored_count += 1
            print(f"🔄 恢复帮助菜单项: {item_data.get('item_label')}")
        
        # 保存修改
        navbar_settings.save()
        
        # 删除备份文件
        os.remove(backup_path)
        
        print(f"✅ 成功恢复 {restored_count} 个帮助菜单项")
        return True
        
    except Exception as e:
        frappe.log_error(f"恢复帮助下拉菜单配置时出错: {str(e)}")
        print(f"❌ 恢复帮助下拉菜单配置失败: {str(e)}")
        return False


def get_current_help_dropdown_items():
    """
    获取当前的帮助下拉菜单项列表
    
    Returns:
        list: 当前菜单项的标签列表
    """
    try:
        navbar_settings = frappe.get_single("Navbar Settings")
        return [item.item_label for item in navbar_settings.help_dropdown]
    except Exception as e:
        frappe.log_error(f"获取帮助下拉菜单项时出错: {str(e)}")
        return []


def clean_navbar_backup_files():
    """
    清理所有的navbar备份文件
    """
    try:
        backup_dir = os.path.join(frappe.get_app_path("theme"), "backups")
        
        if not os.path.exists(backup_dir):
            return
        
        # 删除所有navbar相关的备份文件
        backup_files = [f for f in os.listdir(backup_dir) if f.startswith("navbar_help_dropdown_backup_")]
        
        for backup_file in backup_files:
            backup_path = os.path.join(backup_dir, backup_file)
            os.remove(backup_path)
            print(f"🗑️ 清理备份文件: {backup_file}")
        
        print(f"✅ 清理了 {len(backup_files)} 个navbar备份文件")
        
    except Exception as e:
        frappe.log_error(f"清理navbar备份文件时出错: {str(e)}")
        print(f"❌ 清理navbar备份文件失败: {str(e)}")